package com.sunjob.mrogeteway.filter;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.sunjob.common.constant.MROConstant;
import com.sunjob.common.result.Result;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sun.reflect.annotation.AnnotationType;

import java.lang.annotation.Annotation;
import java.nio.charset.StandardCharsets;
import java.util.List;


/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-01 22:31
 */
@Component
@Order(1)
public class MROGlobalFilter implements GlobalFilter{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获得请求对象
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        HttpCookie satoken = cookies.toSingleValueMap().get("satoken");
       String cookieValue = null;
       if(satoken!=null){
           cookieValue=  satoken.getValue();
       }
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String paramValue = queryParams.toSingleValueMap().get("satoken");
        HttpHeaders headers = request.getHeaders();
        String headerValue = headers.getFirst("satoken");
        String loginId = null;
        if(cookieValue!=null){
            loginId = (String) StpUtil.getLoginIdByToken(cookieValue);
        }else if(paramValue!=null){
            loginId = (String)StpUtil.getLoginIdByToken(paramValue);
        }else if(headerValue!=null){
            loginId = (String)StpUtil.getLoginIdByToken(headerValue);
        }
        if(loginId==null){
            // 未登录
            ServerHttpResponse response = exchange.getResponse();
            response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
            DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONString(Result.fail(MROConstant.USER_NOT_LOGIN)).getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(wrap));
        }
        return chain.filter(exchange);
    }
}
